package cn.xianyang.basic.controller;

import cn.xianyang.basic.dto.EmailRegisterDto;
import cn.xianyang.basic.dto.RegisterDto;
import cn.xianyang.basic.exception.BusinessException;
import cn.xianyang.basic.service.IVerifyCodeService;
import cn.xianyang.basic.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 验证码接口
 *
 */
@RestController
@RequestMapping("/verifyCode")
public class VerifyCodeController {

    @Autowired
    private IVerifyCodeService verifyCodeService;

    /**
     * 图形验证码
     * @param key
     * @return
     */
    @GetMapping("/image/{imageCodeKey}")
    public AjaxResult imageCodeKey(@PathVariable("imageCodeKey") String key){
        try {
            String base64Str = verifyCodeService.imageCodeKey(key);
            return AjaxResult.me().setResultObj(base64Str);
        } catch (BusinessException e) { //自己的业务异常自己通过自定义BusinessException处理
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("保存对象失败！"+e.getMessage());
        }
    }

    /**
     * 发送短信验证码
     * @param dto
     * @return
     */
    @PostMapping("/smsCode")
    public AjaxResult smsCode(@RequestBody RegisterDto dto){
        try {
            verifyCodeService.smsCode(dto);
            return AjaxResult.me();
        } catch (BusinessException e) { //自己的业务异常自己通过自定义BusinessException处理
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("保存对象失败！"+e.getMessage());
        }
    }

    /**
     * 发送邮箱验证码
     * @param dto
     * @return
     */
    @PostMapping("/sendEmailCode")
    public AjaxResult emailCode(@RequestBody EmailRegisterDto dto){
        try {
            verifyCodeService.emailCode(dto);
            return AjaxResult.me();
        } catch (BusinessException e) { //自己的业务异常自己通过自定义BusinessException处理
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("服务器忙,稍后在重试"+e.getMessage());
        }
    }
}
